package com.fantasy.testjavascript;

import java.util.Date;
import java.util.HashMap;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.fantasy.test.model.UserTest;

public class ScriptEngineTest2 {

	public static void main(String[] args) {
		
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("javascript");
		engine.put("a", new Date());
		engine.put("b", "");
		//engine.put("has", "function(userId){if(userId=='fantasy'){return 'fan'}}");
		HashMap<String , String > map = new HashMap<String , String >();
		map.put("aa", "i m a");
		map.put("bb" , "i m b");
		
		engine.put("map",map);
		
		UserTest u = new UserTest();
		
		u.setUserName("fantasy");
		u.setUserPwd("666666");
		
		engine.put(u.getClass().getName(), u);
		
		
		
		try {
			// 只能为Double，使用Float和Integer会抛出异常

			Date result = (Date) engine.eval("a ");

			System.out.println("result = " + result);
			
			System.out.println("-===============->>>>>>>>>>>>>>");
			engine.put("UsrtTest", u);
			//engine.eval("var u = new UserTest();");
			//engine.eval("u.setUserName('fantasy');");
			//System.out.println(engine.eval("u.getUserName();"));
			engine.eval("if(map.get('aa') != '' ){map.put('aa' , 'i m fantasy')}");
			System.out.println(engine.eval("map"));
			System.out.println("++++");
			System.out.println(engine.eval("map.get('cc') == null"));
			System.out.println(engine.eval("map.get('aa') == \"\""));
			
			engine.eval("function has(userId){if(userId=='fantasy'){return 'fan'}else{return 'aaaaaaaaaa'}}");
			System.out.println(engine.eval("has('fantasy')"));
			System.out.println(engine.eval("has('hayden')"));
		} catch (ScriptException e) {
			e.printStackTrace();
		}

	}

}